<template>
  <div>
    <a-card :bordered="false" style="margin-bottom: 10px;">
      <!-- 条件搜索 -->
      <div class="table-page-search-wrapper">
        <a-form :labelCol="labelCol" :wrapperCol="wrapperCol" ref="queryForm">
          <a-row :gutter="32">
            <a-col :span="6">
              <a-form-item label="日期">
                <a-range-picker format="YYYY-MM-DD" v-model="orderDate" :show-today="true" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="操作员">
                <select-user v-model="operator" select-model="single" />
              </a-form-item>
            </a-col>
            <a-col>
              <span class="table-page-search-submitButtons" style="float: right;">
                <a-button type="primary" @click="handleQuery"><a-icon type="search" />查询</a-button>
                <a-button style="margin-left: 8px" @click="resetQuery"><a-icon type="redo" />重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card :bordered="false" class="table-card">
      <advance-table :key="tableKey" :title="title" :pagination="{
        current: queryParam.pageNum,
        pageSize: queryParam.pageSize,
        total: total,
        showSizeChanger: true,
        pageSizeOptions: pageSizeOptions,
        showLessItems: true,
        showQuickJumper: true,
        showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，总计 ${total} 条`,
        onChange: changeSize,
        onShowSizeChange: onShowSizeChange
      }" tableKey="base-bizOrder-index-table" @change="handleTableChange" rowKey="id" @refresh="getList"
        :components="drag(columns)" :columns="columns" :data-source="dataList" :loading="loading"
        :format-conditions="true">
        <div class="table-operations" slot="button">
          <!-- <a-button type="primary"  @click='print'>
            <a-icon />打印
          </a-button> -->
          <a-button type="primary" v-hasPermi="['biz:bizReportPieceProduction:export']" :loading="exportLoading"  @click='exportData'>
            <a-icon />导出
          </a-button>
        </div>
      </advance-table>
    </a-card>


    <ant-modal :visible="openPrint" modal-title="打印应收账款明细" :adjust-size="true" @cancel="openPrint = false"
      modalHeight="550" modalWidth="1000">
      <a-row slot="content">
        <iframe height='425' width='985' style='border:none;' :src='setUrl'></iframe>
      </a-row>
      <div slot="footer">
        <a-button @click="openPrint = false">关闭</a-button>
      </div>
    </ant-modal>
  </div>
</template>
<script>
import { listPieceProduction } from '@/api/biz/bizReport'
import AdvanceTable from '@/components/pt/table/AdvanceTable'
import tableDragResizeMixin from '@/mixins/tableDragResizeMixin'
import storage from 'store'
import listMixin from '@/mixins/listMixin';
import { ACCESS_TOKEN } from '@/store/mutation-types'
import AntModal from '@/components/pt/dialog/AntModal'
import SelectUser from '@/components/pt/selectUser/SelectUser'
import XLSX from 'xlsx/xlsx' 
export default {
  name: 'pieceProduction',
  components: {
    AdvanceTable,
    AntModal,
    SelectUser
  },
  mixins: [tableDragResizeMixin, listMixin],
  data() {
    return {
      printUrl: '/api/biz/bizOrder/printPieceProductionList?Authorization=' + storage.get(ACCESS_TOKEN),
      printUrlPath: '/api/biz/bizOrder/printPieceProductionList?Authorization=' + storage.get(ACCESS_TOKEN),
      openPrint: false,
      showAddModal: false,
      setUrl: '',
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      orderDate: undefined,
      // 选中的主键集合
      selectedRowKeys: [],
      // 选中的数据集合
      selectedRows: [],
      // 高级搜索 展开/关闭
      advanced: false,
      open: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // label的百分比
      labelCol: { span: 6 },
      // 内容区域的百分比
      wrapperCol: { span: 18 },
      // 表格数据
      dataList: [],
      // 查询参数
      title: '生产计件',
      tableKey: '0',
      operator: {},
      queryParam: {
        pageNum: 1,
        pageSize: 11,
        supplierName: undefined
      },
      pageSizeOptions: ['11', '21', '31', '101', '201'],
      listFunc: (param) => listPieceProduction(param),
      columns: [],
      exportLoading:false,//导出loading
    }
  },
  created() {
    // this.initColumnsSetting()
    // 生成columns
    this.addColumns()
  },
  methods: {

    /** 查询销售单列表 */
    getList() {

      if (this.orderDate && this.orderDate.length > 0) {
        this.queryParam.startDate = this.orderDate[0].format('yyyy-MM-DD');
      } else {
        this.queryParam.startDate = undefined;
      }
      if (this.orderDate && this.orderDate.length > 1) {
        this.queryParam.endDate = this.orderDate[1].format('yyyy-MM-DD');
      } else {
        this.queryParam.endDate = undefined;
      }
      this.queryParam.creator = this.operator.ids || ''
      let param = this.getQueryParam()
      this.loading = true
      listPieceProduction(param).then(response => {
        let dataList = response.data.list
        dataList.forEach(val => {
          let total = 0
          if (val.pieceProductionRecordVos.length) {
            val.pieceProductionRecordVos.forEach(v => {
              val[`${v.id}processVol`] = v.processVol
              val[`${v.id}unitSalary`] = v.unitSalary
              total = this.$toDecimal(total + (v.processVol || 0) * (v.unitSalary || 0))
            })
          }
          val.total = total
        });
        this.dataList = dataList
        this.total = response.data.total
        this.loading = false
        this.tableAddTotalRow(this.columns, this.dataList)
      })
    },

    
    /** 查询销售单列表 */
    getAllList() {
      return new Promise((resolve, reject) => {
        if (this.orderDate && this.orderDate.length > 0) {
          this.queryParam.startDate = this.orderDate[0].format('yyyy-MM-DD');
        } else {
          this.queryParam.startDate = undefined;
        }
        if (this.orderDate && this.orderDate.length > 1) {
          this.queryParam.endDate = this.orderDate[1].format('yyyy-MM-DD');
        } else {
          this.queryParam.endDate = undefined;
        }
        this.queryParam.creator = this.operator.ids || ''
        let param = Object.assign({}, this.queryParam, { pageSize: this.total })
        listPieceProduction(param).then(response => {
          let dataList = response.data.list
          dataList.forEach(val => {
            let total = 0
            if (val.pieceProductionRecordVos.length) {
              val.pieceProductionRecordVos.forEach(v => {
                val[`${v.id}processVol`] = v.processVol
                val[`${v.id}unitSalary`] = v.unitSalary
                total = this.$toDecimal(total + (v.processVol || 0) * (v.unitSalary || 0))
              })
            }
            val.total = total
          });
          this.tableAddTotalRow(this.columns, dataList)
          resolve(dataList)
        })
      })
    },
    getQueryParam() {
      return Object.assign({}, this.queryParam, { pageSize: this.queryParam.pageSize - 1 })
    },

    cancel() {
      this.open = false;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParam.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParam = {
        pageNum: 1,
        pageSize: 10,
      }
      this.orderDate = undefined
      this.operator = {}
      this.handleQuery()
    },
    /** 翻页操作 */
    onShowSizeChange(current, pageSize) {
      this.queryParam.pageSize = pageSize
      this.getList()
    },
    /** 翻页操作 */
    onSizeChange(current, size) {
      this.queryParam.pageNum = 1
      this.queryParam.pageSize = size
      this.getList()
    },
    /** 翻页操作 */
    changeSize(current, pageSize) {
      this.queryParam.pageNum = current
      this.queryParam.pageSize = pageSize
      this.getList()
    },
    /** 翻页操作 */
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      this.ids = this.selectedRows.map(item => item.id)
      this.single = selectedRowKeys.length !== 1
      this.multiple = !selectedRowKeys.length
    },
    handleTableChange(pagination, filters, sorter) {
      if (sorter.field !== undefined && sorter.field !== null && sorter.field !== '') {
        this.queryParam.orderByColumn = 'a.' + sorter.field
        this.queryParam.isAsc = sorter.order
      }
      this.getList()
    },

    /**
     * @打印
     * @returns 
     */
    print() {
      let param = {}
      if (this.operator.ids) {
        param = {
          ids: this.operator.ids
        }
      } else {
        return this.$message.error('请选择员工')
      }
      this.setUrl = `${this.printUrl}&creator=${param.ids}`
      this.openPrint = true;
    },
    async addColumns() {
      let processList = await this.getProcessList()
      this.columns = [
        {
          title: '日期',
          dataIndex: 'orderDate',
          align: 'center'
        },
        {
          title: '编号',
          dataIndex: 'orderNumber',
          align: 'center'
        },
        {
          title: '客户名称',
          dataIndex: 'customerName',
          align: 'center'
        },
        {
          title: '地址',
          dataIndex: 'address',
          align: 'center'
        },
        {
          title: '品牌',
          dataIndex: 'brand',
          ellipsis: true,
          align: 'center',
        },
        {
          title: '颜色',
          dataIndex: 'color',
          ellipsis: true,
          align: 'center',
        },
        {
          title: '型号',
          dataIndex: 'model',
          ellipsis: true,
          align: 'center',
        },
        {
          title: '规格',
          dataIndex: 'spec',
          ellipsis: true,
          align: 'center',
        },
      ]
      let customColumns = processList.map(v => {
        let obj = {
          title: v.processName,
          align: 'center',
          children: [
            {
              title: '数量',
              dataIndex: `${v.id}processVol`,
              align: 'center'
            },
            {
              title: '单价',
              dataIndex: `${v.id}unitSalary`,
              align: 'center'
            },

          ]
        }
        return obj
      })
      this.columns.push(...customColumns)
      let lastCol = {
        title: '金额',
        dataIndex: 'total',
        align: 'center'
      }
      this.columns.push(lastCol)
      console.log('object :>> ', this.buildHeader(this.columns));
      this.tableKey = 1
      this.getList()
    },


    /** 导出开始------------------------ */
    /**
         * 构建excel表头
         * @param columns 列表页面展示的表头
         * @returns {[]} excel表格展示的表头
         */
    buildHeader(columns) {
      let excelHeader = [];
      // 构建生成excel表头需要的数据结构
      this.getHeader(columns, excelHeader, 0, 0);
      // 多行表头长短不一，短的向长的看齐，不够的补上行合并占位符
      let max = Math.max(...(excelHeader.map(a => a.length)))
      excelHeader.filter(e => e.length < max).forEach(
        e => this.pushRowSpanPlaceHolder(e, max - e.length))
      return excelHeader;
    },

    /**
     * 生成头部 
     * @param headers 展示的头部
     * @param excelHeader excel头部
     * @param deep 深度
     * @param perOffset 前置偏移量
     * @returns {number}  后置偏移量
     */
    getHeader(headers, excelHeader, deep, perOffset) {
      let offset = 0
      let cur = excelHeader[deep]
      if (!cur) {
        cur = excelHeader[deep] = []
      }
      // 填充行合并占位符
      this.pushRowSpanPlaceHolder(cur, perOffset - cur.length)
      for (let i = 0; i < headers.length; i++) {
        let head = headers[i]
        cur.push(head.title)
        if (head.hasOwnProperty('children') && Array.isArray(head.children)
          && head.children.length > 0) {
          let childOffset = this.getHeader(head.children, excelHeader, deep + 1,
            cur.length - 1)
          // 填充列合并占位符
          this.pushColSpanPlaceHolder(cur, childOffset - 1)
          offset += childOffset
        } else {
          offset++
        }
      }
      return offset;

    },

        /**
         * 填充行合并占位符
         * */
         pushRowSpanPlaceHolder(arr, count) {
          for (let i = 0; i < count; i++) {
            arr.push('!$ROW_SPAN_PLACEHOLDER')
          }
        },

        // 填充列合并占位符
        pushColSpanPlaceHolder(arr, count) {
          for (let i = 0; i < count; i++) {
            arr.push('!$COL_SPAN_PLACEHOLDER')
          }
        },

        flatData(list, eachDataCallBack) {
          let resultList = [];
          for (let i = 0; i < list.length; i++) {
            let data = list[i];
            let rawDataList = [];
            // 每个子元素都父元素合并成一条数据
            data['rowSpan'] = 1;
            rawDataList.push(data);
            resultList.push(...rawDataList);
            if (typeof eachDataCallBack === 'function') {
              eachDataCallBack(rawDataList)
            }
          }
          return resultList;
        },
        // 扁平头部
        flat(columns) {
          let result = []
          columns.forEach(e => {
            if (e.hasOwnProperty('children')) {
              result.push(...this.flat(e.children))
            } else if (e.hasOwnProperty('exeFun')) {
              result.push(e)
            } else if (e.hasOwnProperty('dataIndex')) {
              result.push(e)
            }
          })
          return result;
        },
        s2ab(s) {
          let buf = new ArrayBuffer(s.length);
          let view = new Uint8Array(buf);
          for (let i = 0; i !== s.length; ++i) {
            view[i] = s.charCodeAt(i) & 0xFF;
          }
          return buf;
        },
        openDownloadXLSXDialog(url, saveName) {
          if (typeof url == 'object' && url instanceof Blob) {
            url = URL.createObjectURL(url); // 创建blob地址
          }
          var aLink = document.createElement('a');
          aLink.href = url;
          aLink.download = saveName || ''; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
          var event;
          if (window.MouseEvent) {
            event = new MouseEvent('click');
          } else {
            event = document.createEvent('MouseEvents');
            event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false,
              false, false, false, 0, null);
          }
          aLink.dispatchEvent(event);
        },

        async exportData() {
          this.exportLoading = true
          let list = await this.getAllList()
          if (!Array.isArray(list) || list.length < 1) {
            this.$message.error('可导出数据为空！')
            this.exportLoading = false
            return;
          }
          let sheetName = '生产计件报表' + new Date().toLocaleDateString('en-CA');
          // excel表头
          let excelHeader = this.buildHeader(this.columns);
          // 头部行数，用来固定表头
          let headerRows = excelHeader.length;
          // 提取数据
          let dataList = this.extractData(list, this.columns);
          excelHeader.push(...dataList, []);
          // 计算合并
          let merges = this.doMerges(excelHeader)
          // 生成sheet
          let ws = this.aoa_to_sheet(excelHeader, headerRows);
          // 单元格合并
          ws['!merges'] = merges;
          // 头部冻结
          ws["!freeze"] = {
            xSplit: "1",
            ySplit: "" + headerRows,
            topLeftCell: "B" + (headerRows + 1),
            activePane: "bottomRight",
            state: "frozen",
          };
          // 列宽
          ws['!cols'] = [{wpx:165}];
          let workbook = {
            SheetNames: [sheetName],
            Sheets: {}
          };
          workbook.Sheets[sheetName] = ws;
          // excel样式
          let wopts = {
            bookType: 'xlsx',
            bookSST: false,
            type: 'binary',
            cellStyles: true
          };
          let wbout = XLSX.write(workbook, wopts);
          let blob = new Blob([this.s2ab(wbout)], { type: "application/octet-stream" });
          this.openDownloadXLSXDialog(blob, sheetName + '.xlsx')
          
          this.exportLoading = false
        },
        /**
        * 根据选中的数据和展示的列，生成结果
        * @param dataList
        * @param columns
        */
        extractData(dataList, columns) {
          // 列
          let headerList = this.flat(columns);
          console.log('dataList :>> ', dataList);
          // 导出的结果集
          let excelRows = [];
          // 如果有child集合的话会用到
          let dataKeys = new Set(Object.keys(dataList[0]));
          this.flatData(dataList, (list) => {
            excelRows.push(...this.buildExcelRow(dataKeys, headerList, list));
          })
          return excelRows;
        },

        /**
         *
         * 
         * */
         buildExcelRow(mainKeys, headers, rawDataList) {
          // 合计行
          let sumCols = [];
          // 数据行
          let rows = [];
          for (let i = 0; i < rawDataList.length; i++) {
            let cols = []
            let rawData = rawDataList[i];
            // 提取数据
            for (let j = 0; j < headers.length; j++) {
              let header = headers[j];
              // 父元素键需要行合并
              if (rawData['rowSpan'] === 0 && mainKeys.has(header.dataIndex)) {
                cols.push('!$ROW_SPAN_PLACEHOLDER')
              } else {
                let value;
                if (typeof header.exeFun === 'function') {
                  value = header.exeFun(rawData);
                } else {
                  value = rawData[header.dataIndex];
                }
                cols.push(value)
                // 如果该列需要合计,并且是数字类型
                if (header['summable'] && typeof value === 'number') {
                  sumCols[j] = (sumCols[j] ? sumCols[j] : 0) + value;
                }
              }
            }
            rows.push(cols);
          }
          // 如果有合计行
          if (sumCols.length > 0) {
            rows.push(...this.sumRowHandle(sumCols));
          }
          return rows;
        },

        sumRowHandle(sumCols) {
          //TODO
          return [];
        },
        /**
         * 合并头部单元格
         **/
        doMerges(arr) {
          // 要么横向合并 要么纵向合并
          let deep = arr.length;
          let merges = [];
          for (let y = 0; y < deep; y++) {
            // 先处理横向合并
            let row = arr[y];
            let colSpan = 0
            for (let x = 0; x < row.length; x++) {
              if (row[x] === '!$COL_SPAN_PLACEHOLDER') {
                row[x] = undefined;
                if(x+1 === row.length){
                  merges.push({ s: { r: y, c: x - colSpan - 1}, e: { r: y, c: x } })
                }
                colSpan++
              } else if (colSpan > 0 && x > colSpan) {
                merges.push({ s: { r: y, c: x - colSpan - 1 }, e: { r: y, c: x - 1 } })
                colSpan = 0
              } else {
                colSpan = 0
              }
            }
          }
          // 再处理纵向合并
          let colLength = arr[0].length
          for (let x = 0; x < colLength; x++) {
            let rowSpan = 0
            for (let y = 0; y < deep; y++) {
              if (arr[y][x] === '!$ROW_SPAN_PLACEHOLDER') {
                arr[y][x] = undefined;
                rowSpan++;
                if(y+1 === deep){
                  merges.push({ s: { r: y - rowSpan , c: x }, e: { r: y , c: x } })
                }
                
              } else if (rowSpan > 0 && y > rowSpan) {
                merges.push({ s: { r: y - rowSpan - 1, c: x }, e: { r: y - 1, c: x } })
                rowSpan = 0;
              } else {
                rowSpan = 0;
              }
            }
          }
          return merges;
        },

        /**
         * 从github复制过来的
         */
        aoa_to_sheet(data, headerRows) {
          const ws = {};
          const range = { s: { c: 10000000, r: 10000000 }, e: { c: 0, r: 0 } };
          for (let R = 0; R !== data.length; ++R) {
            for (let C = 0; C !== data[R].length; ++C) {
              if (range.s.r > R) {
                range.s.r = R;
              }
              if (range.s.c > C) {
                range.s.c = C;
              }
              if (range.e.r < R) {
                range.e.r = R;
              }
              if (range.e.c < C) {
                range.e.c = C;
              }
              /// 这里生成cell的时候，使用上面定义的默认样式
              const cell = {
                v: data[R][C] || '',
                s: {
                  font: { name: "宋体", sz: 11, color: { auto: 1 } },
                  alignment: {
                    /// 自动换行
                    wrapText: 1,
                    // 居中
                    horizontal: "center",
                    vertical: "center",
                    indent: 0
                  }
                }
              };
              // 头部列表加边框
              if (R < headerRows) {
                cell.s.border = {
                  top: { style: 'thin', color: { rgb: "000000" } },
                  left: { style: 'thin', color: { rgb: "000000" } },
                  bottom: { style: 'thin', color: { rgb: "000000" } },
                  right: { style: 'thin', color: { rgb: "000000" } },
                };
                cell.s.fill = {
                  patternType: 'solid',
                  fgColor: { theme: 3, "tint": 0.3999755851924192, rgb: 'DDD9C4' },
                  bgColor: { theme: 7, "tint": 0.3999755851924192, rgb: '8064A2' }
                }
              }
              const cell_ref = XLSX.utils.encode_cell({ c: C, r: R });
              if (typeof cell.v === 'number') {
                cell.t = 'n';
              } else if (typeof cell.v === 'boolean') {
                cell.t = 'b';
              } else {
                cell.t = 's';
              }
              ws[cell_ref] = cell;
            }
          }
          if (range.s.c < 10000000) {
            ws['!ref'] = XLSX.utils.encode_range(range);
          }
          return ws;
        },
    /** 导出结束 -------------------------- */
  }
}
</script>
